package com.ikun.controller;

import com.ikun.core.enums.FileTypeEnum;
import com.ikun.core.plugin.storage.StorageDriver;
import com.ikun.core.pojo.dto.FileUploadDTO;
import com.ikun.core.pojo.vo.UploadFilesVo;
import com.ikun.core.utils.R;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.MediaType;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;

@Slf4j
@Tag(name = "文件管理", description = "文件管理接口")
@RestController
@RequestMapping("/file")
public class FileController {

    /**
     * 上传文件
     */
    @Operation(summary = "上传文件") //consumes 指定该方法只处理特定Content-Type的请求
    @PostMapping(value = "/upload", consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
    public R<UploadFilesVo> uploadFile(@Validated FileUploadDTO dto) throws IOException {
        MultipartFile file = dto.getFile();
        log.info("dto: {}", dto);
        log.info("fileContentType: {}, fileName: {}, fileSize: {}",
                file.getContentType(), file.getOriginalFilename(), file.getSize());
        // TODO: 业务逻辑处理（检查 hash 是否已存在、保存文件、入库等）


        // 获取扩展名
        String originalFilename = file.getOriginalFilename();
        String extension = null;
        String mimeType = file.getContentType();

        if (originalFilename != null && originalFilename.contains(".")) {
            extension = originalFilename.substring(originalFilename.lastIndexOf(".") + 1);
        }
        System.out.println("extension ====== " + extension);
        // 自动分类
        FileTypeEnum fileType = FileTypeEnum.resolve(extension, mimeType);

        StorageDriver storageDriver = new StorageDriver();
        UploadFilesVo vo = storageDriver.upload(file, fileType);
        return R.success(vo);
    }

}
